package com.bawei.module_home.search

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_home.R
import com.bawei.module_home.home.model.entity.VideoEntity
import com.bumptech.glide.Glide

class SearchResultAdapter(
    private val onItemClick: (VideoEntity) -> Unit
) : RecyclerView.Adapter<SearchResultAdapter.ViewHolder>() {

    private val videoList = mutableListOf<VideoEntity>()

    fun updateData(newList: List<VideoEntity>) {
        videoList.clear()
        videoList.addAll(newList)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_search_result, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val video = videoList[position]
        holder.bind(video)
    }

    override fun getItemCount(): Int = videoList.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val ivVideoCover: ImageView = itemView.findViewById(R.id.iv_video_cover)
        private val tvVideoTitle: TextView = itemView.findViewById(R.id.tv_video_title)
        private val tvVideoDescription: TextView = itemView.findViewById(R.id.tv_video_description)
        private val tvPlayCount: TextView = itemView.findViewById(R.id.tv_play_count)

        init {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    onItemClick(videoList[position])
                }
            }
        }

        fun bind(video: VideoEntity) {
            tvVideoTitle.text = video.title
            tvVideoDescription.text = video.description
            tvPlayCount.text = "${video.playnum}次播放"

            // 加载视频封面
            Glide.with(itemView.context)
                .load(video.videomainimag)
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.placeholder_image)
                .into(ivVideoCover)
        }
    }
} 